package com.example.backend.controller;


import com.example.backend.entity.User;
import com.example.backend.entity.UserInfo;
import com.example.backend.service.UserService;
import com.example.backend.util.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Object login(@RequestBody User user ) {

        if (userService.findByUsernameAndPassword(user.getUsername(),user.getPassword())){
            User u = userService.findUser(user.getUsername());

            String token = TokenService.getToken(u);
            UserInfo userInfo=new UserInfo();
            userInfo.setUsername(u.getUsername());
            userInfo.setToken(token);
            userInfo.setPermission(u.getPermission());
            System.out.println(userInfo);
            return userInfo;
        }
        else{
            return false;
        }

    }
    @PostMapping("/insert")
    public void insert (@RequestBody User user){
        userService.insert(user);
    }
    @GetMapping("/register")
    public boolean findByUsername(@Param("username") String username){
        return userService.findByUsername(username);
    }

    @GetMapping("/delete")
    public void delete(@Param("id") Integer id){
        userService.delete(id);
    }

    @GetMapping("/list")
    public List<User> findAll(){
        return userService.findAll();
    }
    @GetMapping("/search")
    public List<User> findUserByName(@Param("key") String key, @Param("value") String value){
        System.out.println(key);
        System.out.println(value);

        switch (key){
            case "username":
                User u =userService.findUser(value);
                return List.of(u);
            case "password":return userService.findByPassword(value);
            case "permission":return userService.findByPermission(Integer.parseInt(value));
            case "id": return userService.findById(Integer.parseInt(value));
            default:break;
        }
        return null;
    }
}
